package atomic

import java.util.concurrent.atomic.AtomicInteger

/***
 * CAS操作的简单示例
 */
class Task {
    private val atomicInteger = AtomicInteger(0)

    fun autoIncrement() {
        atomicInteger.incrementAndGet()
    }

    fun result() = atomicInteger.get()
}

fun main() {
    val task = Task()

    val thread = Thread {
        for (index in 0..100) {
            Thread.sleep(20)
            task.autoIncrement()
            println("${Thread.currentThread().name}-result:${task.result()}")
        }
    }
    thread.name = "thread1"

    val thread1 = Thread {
        for (index in 0..100) {
            Thread.sleep(20)
            task.autoIncrement()
            println("${Thread.currentThread().name}-result:${task.result()}")
        }
    }
    thread1.name = "thread2"

    thread.priority=3

    thread.start()
    thread1.start()

    Thread.sleep(5000)
    println("total result:${task.result()}")

    //TODO(自增的过程并没有从1加到202，但是最后的结果是对的，是如何保证结果是正确的？)
}